//
//  kHandle.m
//  Brand
//
//  Created by Lin Eidan on 14-5-19.
//  Copyright (c) 2014年 Faker. All rights reserved.
//

#import "kHandle.h"
#import "VideoPlayerViewController.h"
#import "Header.h"
#import "config.h"
#import "CarouselObj.h"
#import "M3U8DownloadConfig.h"


#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"



static const int ddLogLevel = LOG_LEVEL_VERBOSE;

//加油评分弹出
#define UserDataGoToAppStoreKey                 @"userDataGoToAppStoreKey"
#define UserDataGoToAppStoreFirstRunDateKey     @"userDataGoToAppStoreFirstRunDateKey"
#define UserDataGoToAppStoreDateKey             @"userDataGoToAppStoreDateKey"

//每3天检测一次版本更新。
#define UserDataCheckNewVersionDataKey          @"userDataCheckNewVersionDataKey"

#define AlertViewTagThatAddScore        10000
#define AlertViewTagThatCheckNewVersion 10001

@interface kHandle()

@property (strong, nonatomic) HTTPServer *httpServer;
@property (assign, nonatomic) BOOL is3GUseAlertViewDisplay;

@end

@implementation kHandle

+ (kHandle *)sharedInstance
{
    static kHandle *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[kHandle alloc] init];
    });
    return _sharedInstance;
}

-(id)init{
    self =[super init];
    if (self) {
        self.isShowTrueView = NO;
        [UIApplication sharedApplication].idleTimerDisabled = YES;    //不会自动锁定
        [Common handleAlwaysSoundIgnoreMuteSwitch];
        [self performSelector:@selector(handleShowTrueViewOrNotWhenFirstLaunch) withObject:nil afterDelay:0.1];
        [self performSelector:@selector(observeTheNetworkTypeChange) withObject:nil afterDelay:0.1];
        [self performSelector:@selector(handle3GAndPushAndWifiCacheLocalDataWhenFirstLaunch) withObject:nil afterDelay:0.2];
        [self performSelector:@selector(restartLocalServer) withObject:nil afterDelay:0.3];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomethingWhenAppDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}

-(void)doSomethingWhenAppDidBecomeActive{
    [self handleShowTrueViewOrNotWhenFirstLaunch];
    [self goToAddScoreAndCheckNewVersion];
    [self prepareGetCircleData];
}

-(void)showTipsWhenRequestFailedWithView:(UIView *)view{
    [PopTips tipsAtTop:view ? view : kApp.rootNav.view Msg:NotifyNoNet];
}

#pragma -mark showTrueView

-(void)handleShowTrueViewOrNotWhenFirstLaunch{
    id temp = [UserDataBasic getObjectForKey:IsAllowedShowTrueView];
    if (temp == nil) {
        NSString * url = [NSString stringWithFormat:@"%@updateVersion&pf=2",API_BASE];
        
        [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            if(isSuccess){
                NSDictionary* dic = responseObj;
                float appVersion = [[dic objectForKey:@"version_number"] floatValue];
            
                if (appVersion >= [APPVersion floatValue]) {  //网上的大于等于本地,显示真的
                    self.isShowTrueView = YES;
                    [kUser setObject:@"1" forKey:IsAllowedShowTrueView];
                }else{
                    self.isShowTrueView = NO;
                    [kUser setObject:@"0" forKey:IsAllowedShowTrueView];
                }
            }
        }];
    }else{
        self.isShowTrueView = [temp boolValue];
    }
}

#pragma -mark 3G

//3g push init
-(void)handle3GAndPushAndWifiCacheLocalDataWhenFirstLaunch{
    NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
    
    if (![userDefault objectForKey:IsAllowedDownloadIn3G]) {
        [userDefault setBool:NO forKey:IsAllowedDownloadIn3G];
        [userDefault synchronize];
    }
    
    if(![userDefault objectForKey:IsAllowedPush])
    {
        [userDefault setBool:YES forKey:IsAllowedPush];
        [userDefault synchronize];
    }
    
}

//网络状态改变。
-(void)observeTheNetworkTypeChange{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkTypeChange) name:AFNetworkingReachabilityDidChangeNotification object:nil];
}

-(void)networkTypeChange{
    
    if (self.videoPlayerVC.moviePlayer && self.videoPlayerVC) {   //在播放页面
        if ([[AFGetData sharedInstance] theNetworkTypeIsNone]) {
            [self.videoPlayerVC noNetWorkToGoBackWithText:NotifyNoNet];
        }else if ([[AFGetData sharedInstance] theNetworkTypeIs3G]){
            [self.videoPlayerVC handleWhenChangeTo3G];
        }
    }else{   //不在播放，在其他页面
        if ([[AFGetData sharedInstance] theNetworkTypeIs3G]) {  //记得改为3g
            [self normalPageHandleInThe3GInView:nil];
        }
    }
    
    //切换到3G网络时，如果不允许下载，下载全部暂停。。
    if ([self isShouldToDisplayTheTipsWithDownloadInThe3G]) {
        [[DownloadVideoManager sharedInstance] removeAllDownloadRequest];
    }
    
    if ([[AFGetData sharedInstance] theNetworkTypeIsWifi]) {   //连入wifi，开始下载。
        [self handleShowTrueViewOrNotWhenFirstLaunch];
    }
    
}

//一般页面，切换成3g的提示。
-(void)normalPageHandleInThe3GInView:(UIView *)view{
    if ([[AFGetData sharedInstance] theNetworkTypeIs3G] && !self.is3GUseAlertViewDisplay) {   //记得改为3g
        self.is3GUseAlertViewDisplay = YES;
        [PopTips tipsAtMiddle:view ? view : kApp.rootNav.view Msg:Notify2GOr3G];
        [self performSelector:@selector(delayHandleWhen3GTipsShow) withObject:nil afterDelay:5];
    }
}

-(void)delayHandleWhen3GTipsShow{
    self.is3GUseAlertViewDisplay = NO;
}


//3g allow download,返回YES，证明需要阻止一下，就是不允许。
-(BOOL)isShouldToDisplayTheTipsWithDownloadInThe3G{
    if ([[AFGetData sharedInstance] theNetworkTypeIs3G]) {  //记得改为3g
        BOOL isAllowedDownloadIn3G = [kUser boolForKey:IsAllowedDownloadIn3G];
        if (!isAllowedDownloadIn3G) {  //不允许下载，需要弹出。
            return YES;
        }else{
            return NO;
        }
    }
    return NO;
}

#pragma mark - 获取轮播图数据
-(void)prepareGetCircleData
{
   
    NSString* url = [NSString stringWithFormat:@"%@scrollView&type=0",API_BASE];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            NSArray* dataArray = (NSArray*)responseObj;
            NSMutableArray* mArray = [NSMutableArray array];
            for (NSDictionary* dic in dataArray) {
               
                CarouselObj* carouseObj = [[CarouselObj alloc]init];
                carouseObj.title = [dic objectForKey:@"title"];
                carouseObj.type = [dic objectForKey:@"type"];
                carouseObj.pic = [dic objectForKey:@"pic"];
                carouseObj.idOrUrl = [dic objectForKey:@"id_url"];
                [mArray addObject:carouseObj];
            }

            [UserDataBasic saveThisObjectArray:mArray forArrayKey:LocalCarouseData]; //存本地
        }
        else{
            
        }
    }];

}

#pragma -mark 本地服务器
-(void)startLocalServer{
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    self.httpServer=[[HTTPServer alloc] init];
    [self.httpServer setType:@"_http._tcp."];
    [self.httpServer setPort:kPort];
    
    NSString *videoDownLoadPath = [LocalFileManage getPathInsideLibraryCachesFolder:kPathVideoDownload];
    [self.httpServer setDocumentRoot:videoDownLoadPath];
    
    NSError *error;
	if(![self.httpServer start:&error])
	{
		DDLogError(@"Error starting HTTP Server: %@", error);
	}
    
}

-(void)restartLocalServer{
    //启动应用的时候，httpServer还为nil，所以这几句代码无所谓。
    [self.httpServer stop:YES];
    [self.httpServer start:nil];
    
    if (!self.httpServer.isRunning || self.httpServer == nil) {
        [self startLocalServer];
    }
}

-(void)stopLocalServer{
    [self.httpServer stop];
    self.httpServer=nil;
}

#pragma -mark 监测新版本和去评分

-(void)goToAddScoreAndCheckNewVersion{
    if (![[DownloadGetData sharedInstance] theNetworkTypeIsNone]) {
        
        //给好评。
        if ([self handleNeedGoToAppStoreToAddScore]) {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:NotifyNormal message:@"求求您大发慈悲给一个好评吧！" delegate:self cancelButtonTitle:@"狠心拒绝" otherButtonTitles:@"赏赐一个", nil];
            alert.tag = AlertViewTagThatAddScore;
            [alert show];
        }else{  //不用去评分
            //检查是否有版本更新。
            if ([Common todayNeedToNewDataOrNotForKey:UserDataCheckNewVersionDataKey everyFewDays:3]) {
                [Common todayHasGetNewDataForKey:UserDataCheckNewVersionDataKey];
                [self performSelector:@selector(checkNewVersionAuto) withObject:nil afterDelay:1];
            }
        }
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == AlertViewTagThatAddScore) {
        if (buttonIndex == 1) {
            [self handleHasGoToAppStoreAddScore];
            [Common goToAppStore];
        }else if (buttonIndex == 0){
            [self handleRejectGoToAppStoreAddScore];
        }
    }else if(alertView.tag == AlertViewTagThatCheckNewVersion){
        if (buttonIndex == 1) {
            [Common goToAppStore];
        }
    }
}

#pragma -mark 加油评分
-(BOOL)handleNeedGoToAppStoreToAddScore{
    BOOL isNeedShow = NO;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int todayDate = [Common getTodayDate];
    
    //处理第一次启动，没有在本地，存在本地，不需要弹出。
    if (![userDefaults objectForKey:UserDataGoToAppStoreFirstRunDateKey]) {
        [userDefaults setInteger:todayDate forKey:UserDataGoToAppStoreFirstRunDateKey];
        [userDefaults synchronize];
        return isNeedShow;
    }else{
        if (![userDefaults integerForKey:UserDataGoToAppStoreDateKey]) {   //没key，就证明一次都没有出现过,判断是否已经是明天了。
            int lastDate = [userDefaults integerForKey:UserDataGoToAppStoreFirstRunDateKey];
            if (todayDate != lastDate) {
                isNeedShow = YES;
                return isNeedShow;
            }else{
                return NO;
            }
        }else{   //有key了，就是已经出现过了。就直接进行下面的判断
            
        }
    }
    
    if (![userDefaults objectForKey:UserDataGoToAppStoreKey]) {
        if ([userDefaults integerForKey:UserDataGoToAppStoreDateKey]) {
            int lastDate = [userDefaults integerForKey:UserDataGoToAppStoreDateKey];
            
            if (lastDate > todayDate || todayDate > lastDate + 1 ) {
                isNeedShow = YES;
            }
        }else{  //如果重来都没有存过，那么就是没有取到过，需要去取。
            isNeedShow = YES;
        }
    }
    return isNeedShow;
}

-(void)handleHasGoToAppStoreAddScore{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"has" forKey:UserDataGoToAppStoreKey];
    [Common todayHasGetNewDataForKey:UserDataGoToAppStoreDateKey];
    [userDefaults synchronize];
}

-(void)handleRejectGoToAppStoreAddScore{
    [Common todayHasGetNewDataForKey:UserDataGoToAppStoreDateKey];
}

#pragma mark - 检测新版本
-(void)checkNewVersionAuto{
    NSString * url = [NSString stringWithFormat:@"%@updateVersion&pf=2",API_BASE];
    
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess){
            NSDictionary* dic = responseObj;
            float appVersion = [[dic objectForKey:@"version_number"] floatValue];
            if (appVersion > [APPVersion floatValue]) {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:NotifyNormal message:NotifyVersionHave delegate:self cancelButtonTitle:@"再等等" otherButtonTitles:@"立即开启", nil];
                alert.tag = AlertViewTagThatCheckNewVersion;
                [alert show];
            }
        }
    }];
}

//用在播放下载成功的，需要新建，不然会改变下载成功队列中的数据
-(VideoObj *)createANewObjWithOldObject:(VideoObj *)oldObj{
    VideoObj *obj = [[VideoObj alloc] init];
    obj.contentId = oldObj.contentId;
    obj.contentName = oldObj.contentName;
    obj.episodeId = oldObj.episodeId;
    obj.episodeName = oldObj.episodeName;
    obj.type =oldObj.type;
    obj.currentPlayIndex = oldObj.currentPlayIndex;
    obj.percent = oldObj.percent;
    obj.percentLast = oldObj.percentLast;
    obj.imageSrc = oldObj.imageSrc;
    obj.hasPlayDur = oldObj.hasPlayDur;
    obj.isInDownload = oldObj.isInDownload;
    obj.playURL = oldObj.playURL;
    obj.allowResume = oldObj.allowResume;
    obj.isLoading = oldObj.isLoading;
    obj.isComplete = oldObj.isComplete;
    obj.contentLength = oldObj.contentLength;
    obj.downloadRequestURL = oldObj.downloadRequestURL;
    obj.m3u8Handle = oldObj.m3u8Handle;
    obj.m3u8DownloadManage = oldObj.m3u8DownloadManage;
    obj.requestOperaiton = oldObj.requestOperaiton;
    obj.downTask = oldObj.downTask;
    obj.downTaskResumeData = oldObj.downTaskResumeData;
    obj.requestTempFilePath = oldObj.requestTempFilePath;
    obj.length = oldObj.length;
    obj.sourceType = oldObj.sourceType;
    obj.isReadyShow = oldObj.isReadyShow;
    obj.isNeedVIP = oldObj.isNeedVIP;
  
    
    return obj;
}


@end
